package com.ht.controller;

import com.ht.utils.GenUtils;
import com.ht.entity.ColumnsEntity;
import com.ht.entity.TablesEntity;
import com.ht.service.IColumnsService;
import com.ht.service.ITablesService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipOutputStream;

/**
 * @author ht
 * @version 0.1
 * @date 2021/9/26 10:41
 * @email ht035200@163.com
 */
@RestController
@RequestMapping("/sys/generator")
public class GeneratorCodeController {
    @Autowired
    ITablesService tablesService;
    @Autowired
    IColumnsService columnsService;

    /**
     * 生成代码
     */
    @RequestMapping("/code")
    public void code(String tables, HttpServletResponse response) throws IOException {
        byte[] data = generatorCode(tables.split(","));
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"renren.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    private byte[] generatorCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            //查询表信息
            TablesEntity tablesEntity = tablesService.queryTable(tableName);
            //查询列信息
            List<ColumnsEntity> columns = columnsService.queryColumns(tableName);
            //生成代码
            GenUtils.generatorCode(tablesEntity, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}
